#!/usr/bin/env python3
# Flask Web应用主程序
# 功能：提供Web服务并显示服务器信息
from flask import Flask, Response, request
import socket
import subprocess
from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST
import time
import threading

# 创建Flask应用实例
app = Flask(__name__)

# Prometheus指标定义
REQUEST_COUNT = Counter('flask_requests_total', 'Total number of requests', ['method', 'endpoint', 'status'])
REQUEST_DURATION = Histogram('flask_request_duration_seconds', 'Request duration in seconds', ['method', 'endpoint'])
ACTIVE_CONNECTIONS = Gauge('flask_active_connections', 'Number of active connections')
UPTIME_SECONDS = Gauge('flask_uptime_seconds', 'Application uptime in seconds')

# 应用启动时间
start_time = time.time()

# 更新uptime指标的后台线程
def update_uptime():
    while True:
        UPTIME_SECONDS.set(time.time() - start_time)
        time.sleep(10)

# 启动后台线程
uptime_thread = threading.Thread(target=update_uptime, daemon=True)
uptime_thread.start()

def get_server_info():
    """获取服务器信息（主机名和IP地址）"""
    hostname = socket.gethostname()
    try:
        # 尝试多种方法获取IP地址
        # 方法1: 连接到外部地址获取本地IP（最可靠）
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))  # 连接到Google DNS
        primary_ip = s.getsockname()[0]  # 获取本地IP
        s.close()
    except:
        try:
            # 方法2: 使用hostname命令获取IP列表
            result = subprocess.run(['hostname', '-I'], capture_output=True, text=True)
            ip_addresses = result.stdout.strip().split()
            primary_ip = ip_addresses[0] if ip_addresses else socket.gethostbyname(hostname)
        except:
            try:
                # 方法3: 使用socket.gethostbyname作为最后备选
                primary_ip = socket.gethostbyname(hostname)
            except:
                primary_ip = 'Unknown'  # 所有方法都失败时显示未知
    return hostname, primary_ip

@app.route('/')  # 定义根路径路由
def hello():
    """主页处理函数，返回欢迎信息和服务器信息"""
    hostname, ip = get_server_info()
    return f'''
    <h1>Hello World! Flask Web Application is running!</h1>
    <h2>Server Information:</h2>
    <p><strong>Hostname:</strong> {hostname}</p>
    <p><strong>IP Address:</strong> {ip}</p>
    <p><strong>Port:</strong> {{ app_port }}</p>
    <p><strong>Application:</strong> {{ app_name }}</p>
    <p><strong>Version:</strong> {{ app_version }}</p>
    '''

@app.route('/health')
def health_check():
    """健康检查接口"""
    return {'status': 'healthy', 'app': '{{ app_name }}', 'version': '{{ app_version }}'}

@app.route('/metrics')
def metrics():
    """Prometheus metrics端点"""
    return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)

# 请求监控中间件
@app.before_request
def before_request():
    """请求开始时记录时间"""
    app.start_time = time.time()
    ACTIVE_CONNECTIONS.inc()

@app.after_request
def after_request(response):
    """请求结束时记录指标"""
    request_duration = time.time() - app.start_time
    REQUEST_DURATION.labels(method=request.method, endpoint=request.endpoint or 'unknown').observe(request_duration)
    REQUEST_COUNT.labels(method=request.method, endpoint=request.endpoint or 'unknown', status=response.status_code).inc()
    ACTIVE_CONNECTIONS.dec()
    return response

# 应用入口点
if __name__ == '__main__':
    # 启动Flask开发服务器
    # host='0.0.0.0' 允许外部访问
    # port={{ app_port }} 监听指定端口
    app.run(host='0.0.0.0', port={{ app_port }})